package com.hospital.search.module.aop;

import com.hospital.common.dto.search.module.PostInsertDto;
import com.hospital.common.dto.search.module.ReplyInsertDto;
import com.hospital.search.module.exception.SearchServiceException;
import com.hospital.search.module.exception.enums.SearchServiceExpCode;
import com.hospital.search.module.utils.RedisUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

import static com.hospital.common.base.interfaces.Const.POST_NX_PREFIX;
import static com.hospital.common.base.interfaces.Const.REPLY_NX_PREFIX;

@Component
@Aspect
public class ElasticInsertAop {
    @Pointcut("@annotation(com.hospital.search.module.base.annotation.EnableReplyInsertVerify)")
    private void reply(){}
    @Pointcut("@annotation(com.hospital.search.module.base.annotation.EnablePostInsertVerify)")
    private void post(){}
    @Autowired
    private RedisUtils redisUtils;
    @Value("${redis-nx-expire}")
    private Long expire;
    @Before("reply()")
    public void replyVerify(JoinPoint jp){
        // 获取方法参数dto
        Object arg = jp.getArgs()[0];
        if(arg instanceof ReplyInsertDto dto){
            if (dto.getText().length() > 500) {
                throw new SearchServiceException(SearchServiceExpCode.REPLY_TOO_LONG);
            }
            if (!redisUtils.trySetNx(REPLY_NX_PREFIX + dto.getMetaId() +":" + dto.getContentId(), null, expire, TimeUnit.HOURS)){
                throw new SearchServiceException(SearchServiceExpCode.REPLY_EXIST);
            }
        }else {
            throw new SearchServiceException(SearchServiceExpCode.REPLY_TYPE_ERROR);
        }

    }
    @Before("post()")
    public void postVerify(JoinPoint jp){
        // 获取metaId字段
        Object arg = jp.getArgs()[0];
        if (arg instanceof PostInsertDto dto){
            if (!redisUtils.trySetNx(POST_NX_PREFIX + dto.getMetaId(), null, expire, TimeUnit.HOURS)){
                throw new SearchServiceException(SearchServiceExpCode.POST_EXIST);
            }
        }else{
            throw new SearchServiceException(SearchServiceExpCode.POST_TYPE_ERROR);
        }
    }
}
